#include "StdAfx.h"
#include ".\monthrecord.h"
#include "SKTLib.h"
MonthRecord::MonthRecord( const CString& in, const CString& out, const CString& u )
:fin(in)
,fout(out)
,USN(u)
,days(NULL)
,NextMonthFirstDay(NULL)
,MaxDaySize(0)
{
	//allocate memory by init
	init();
	//read day record from fout
}
MonthRecord::~MonthRecord(void)
{
	for(int i=0;i<MaxDaySize;i++)
		if(days[i])
			delete days[i];
	if(days)
		delete [] days;
	
	if(NextMonthFirstDay)
		delete NextMonthFirstDay;
}

void MonthRecord::init()
{
	char drive[256];
	char dir[256];
	char fname[256];
	char ext[256];

	_splitpath(fout.GetBuffer(),drive,dir,fname,ext);

	char* p = strstr(fname,"_");
	ASSERT( p && strlen(p)==4);
	p += 1 ;
	
	char szYear[3];
	ZeroMemory(szYear,3);
	strncpy(szYear,p,2);
	p += 2;
	int year = atoi(szYear)+1911;


	char szMonth[3];
	ZeroMemory(szMonth,3);
	strncpy(szMonth,p,2);
	int month = atoi(szMonth);

	time.SetDate(year,month,1);

	MaxDaySize = GetMaxDay( year,month);

	days = new DayRecord*[MaxDaySize];
	for(int i=0;i<MaxDaySize;i++)
	{
		time.SetDate(year,month,i+1);
		days[i] = new DayRecord(time,USN);
	}

	COleDateTime nextMonth = GetNextMonth(year,month);
	time.SetDate(nextMonth.GetYear(),nextMonth.GetMonth(),1);
	NextMonthFirstDay = new DayRecord(time,USN);
}

void MonthRecord::LoadRecordFromFOUT()
{
	if(!IsExist(fout))
		return;
	FILE* fp = fopen(fout.GetBuffer(),"r");
	
	char line[255];
	DayRecord temp(COleDateTime::GetCurrentTime(),USN);
	while(!feof(fp))
	{
		ZeroMemory(line,255);
		fgets(line,255,fp);
		if(strlen(line)==0)
			continue;
		temp.Parse(line);
		
		COleDateTime nM = GetNextMonth(time.GetYear(),time.GetMonth());
		if( temp.time.GetYear() == nM.GetYear() &&
			temp.time.GetMonth() == nM.GetMonth()&&
			temp.time.GetDay()   == 1 )
		{
			*NextMonthFirstDay = temp;
		}
		if(temp.time.GetYear() == time.GetYear() &&
		   temp.time.GetMonth()== time.GetMonth())
		{
			int i = temp.time.GetDay();
			*days[i-1] = temp;
		}
	}
}